<?php
/**
 * Celebrio FileSystem drivers
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    Celebrio
 * @subpackage FileSystem\Drivers
 */
namespace Celebrio\FileSystem\Drivers;

use Nette\Environment;
use Nette\Object;
use \dibi;

use InvalidArgumentException;

use Celebrio\Core\IModuleInit;
use \Celebrio\Core\DummyInit;

use Celebrio\FileSystem\File;
use Celebrio\FileSystem\FileException;
use Celebrio\FileSystem\Folder;
use Celebrio\FileSystem\DataFile;
use Celebrio\FileSystem\FolderNotFoundException;
use Celebrio\FileSystem\InvalidFilesystemOperation;
use Celebrio\FileSystem\FileNameCollisionException;


/**
 * 
 * @author     pavel
 */
class LocalInit extends DummyInit implements IModuleInit {

    private $realRootPath;
    
//    the errors that were caught in the FS management presenter
//        } catch (FolderNotFoundException $e) {
//            $this->flashMessage(_("Virtual root folder can't be created."), "error");
//        } catch (FileNameCollisionException $e) {
//            $this->flashMessage($e->getMessage(), "error");
//        } catch (InvalidStateException $e) {
//            throw $e; //save config problem
//        } catch (IOException $e) {
//            throw $e; //save config problem
//        } catch (DibiException $e) {
//            $this->flashMessage(_("Problem occured when accessing the database."), "error");
//        }
    
    public function init(array $configuration = array()) {
        Local::setRootPath($configuration["rootPath"]);
    }
    
    /**
     * Creates the root directory of FS.  The new root directory gets
     * 0700 (0777 in development version) access rights for the web-server
     * user (e.g www-data).
     *
     * @param array(string => string) $configuration
     * 
     * @todo change the 0777 permissions to 0700 when running on productin server
     */
    public function install(array $configuration) {
        $mode = 0777;
        //change the number to 0700 when running in the production mode
        $newRoot = new Folder($configuration["rootPath"], true, $mode);
        $this->initDriverStorage();
    }

    public function isAvailable() {
        return true;
    }
    
    /**
     * Checks whether the directory requested to be root exists or whether
     * it can be created. When the requested directory exists,
     * the method tries to use another one inside called "celebriofs". If
     * that one also exists, Exception is thrown.
     */
    public function changeConfig(array $configuration) {
        $path = $configuration["rootPath"];
        try {
            $newRoot = new Folder($path, false);
            //the directory already exists
            try {
                if (substr($path, -1, 1) !== \DIRECTORY_SEPARATOR) {
                    $path = $path . \DIRECTORY_SEPARATOR;
                }
                $path = $path . "celebriofs";
                $newRoot = new Folder($path, false);

                //even the "celebriofs" directory already exists, throw exception
                throw new FileNameCollisionException(_("Directory $path already exists on the local FileSystem drive."));
            } catch (FolderNotFoundException $e) {
                // ok, directory "celebriofs" will be created
            }
        } catch (FolderNotFoundException $e) {
            // ok, directory on user-requested path will be created
        }
        $configuration["rootPath"] = $path;
        return $configuration;
    }
    
    public function formFields() {
        return 
        array(
            array(
                "name" => "rootPath", 
                "label" => "Root path:", 
                "type" => "text", 
                "required" => _('Please provide a path for root directory.')
            ),
        );
    }
    
    private function initDriverStorage() {
        $exists = dibi::fetch("
            SELECT [id_files_storage] 
            FROM [files_storages]
            WHERE [name_files_storage] = %s", "local");
        
        if(!$exists) {
            dibi::query("
                INSERT INTO [files_storages]
                ([name_files_storage]) VALUES (%s)", "local");
        }
    }

}
